const WebSocket = require('ws');
const logger = require('../utils/logger');

class WebSocketServer {
  constructor(server) {
    this.wss = new WebSocket.Server({
      server,
      path: '/alarmEvent',
      verifyClient: (info) => {
        // 允许所有域名的WebSocket连接
        return true;
      }
    });
    this.clients = new Set();
    this.init();
  }

  init() {
    this.wss.on('connection', (ws) => {
      logger.info('New client connected');
      this.clients.add(ws);

      // 设置心跳检测
      /* ws.isAlive = true;
      ws.on('pong', () => {
        ws.isAlive = true;
      }); */

      // 处理客户端消息
      ws.on('message', (message) => {
        logger.info(`Received: ${message}`);
      });

      // 处理连接关闭
      ws.on('close', () => {
        logger.info('Client disconnected');
        this.clients.delete(ws);
      });

      // 启动数据推送
      this.startDataPush(ws);
    });

    // 心跳检测定时器
    setInterval(() => {
      this.wss.clients.forEach((ws) => {
        /* if (!ws.isAlive) {
          return ws.terminate();
        }
        ws.isAlive = false; */
        ws.ping();
      });
    }, 30000);
  }

  // 生成模拟数据
  generateMockData() {
    return {
      timestamp: Date.now(),
      temperature: Math.random() * 30 + 10, // 10-40度之间的随机温度
      humidity: Math.random() * 60 + 20, // 20-80%之间的随机湿度
      pressure: Math.random() * 50 + 980, // 980-1030百帕之间的随机气压
      windSpeed: Math.random() * 20, // 0-20米/秒之间的随机风速
    };
  }

  // 为单个客户端启动数据推送
  startDataPush(ws) {
    const interval = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        const data = this.generateMockData();
        ws.send(JSON.stringify(data));
      } else {
        clearInterval(interval);
      }
    }, 10000); // 每10秒发送一次数据

    ws.on('close', () => {
      clearInterval(interval);
    });
  }
}

module.exports = WebSocketServer;